

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import { authAPI } from '../../services/api';

interface FormData {
  email: string;
  password: string;
  confirmPassword: string;
}

interface FormErrors {
  email: string;
  password: string;
  confirmPassword: string;
}

interface PasswordStrength {
  level: number;
  text: string;
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate();
  
  const [formData, setFormData] = useState<FormData>({
    email: '',
    password: '',
    confirmPassword: ''
  });

  const [formErrors, setFormErrors] = useState<FormErrors>({
    email: '',
    password: '',
    confirmPassword: ''
  });

  const [showPasswordStrength, setShowPasswordStrength] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState<PasswordStrength>({
    level: 0,
    text: ''
  });

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showConfirmPasswordSuccess, setShowConfirmPasswordSuccess] = useState(false);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 用户注册';
    return () => { 
      document.title = originalTitle; 
    };
  }, []);

  // 邮箱格式验证
  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^1[3-9]\d{9}$/;
    return emailRegex.test(email) || phoneRegex.test(email);
  };

  // 密码强度检测
  const checkPasswordStrength = (password: string): PasswordStrength => {
    let strength = 0;
    let feedback = '';
    
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    if (strength <= 2) {
      feedback = '密码强度：弱';
    } else if (strength <= 4) {
      feedback = '密码强度：中等';
    } else {
      feedback = '密码强度：强';
    }
    
    return { level: strength, text: feedback };
  };

  // 显示错误信息
  const showError = (field: keyof FormErrors, message: string) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: message
    }));
  };

  // 隐藏错误信息
  const hideError = (field: keyof FormErrors) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: ''
    }));
  };

  // 邮箱输入处理
  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const email = e.target.value;
    setFormData(prev => ({ ...prev, email }));
    hideError('email');
  };

  const handleEmailBlur = () => {
    const email = formData.email.trim();
    if (email && !validateEmail(email)) {
      showError('email', '请输入有效的邮箱或手机号');
    }
  };

  // 密码输入处理
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const password = e.target.value;
    setFormData(prev => ({ ...prev, password }));
    hideError('password');
    
    if (password.length > 0) {
      setShowPasswordStrength(true);
      const strength = checkPasswordStrength(password);
      setPasswordStrength(strength);
    } else {
      setShowPasswordStrength(false);
    }
    
    // 如果确认密码已输入，重新验证
    if (formData.confirmPassword) {
      validateConfirmPassword(password, formData.confirmPassword);
    }
  };

  // 确认密码验证
  const validateConfirmPassword = (password: string, confirmPassword: string) => {
    if (confirmPassword) {
      if (password === confirmPassword) {
        hideError('confirmPassword');
        setShowConfirmPasswordSuccess(true);
      } else {
        setShowConfirmPasswordSuccess(false);
        showError('confirmPassword', '两次输入的密码不一致');
      }
    } else {
      hideError('confirmPassword');
      setShowConfirmPasswordSuccess(false);
    }
  };

  // 确认密码输入处理
  const handleConfirmPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const confirmPassword = e.target.value;
    setFormData(prev => ({ ...prev, confirmPassword }));
    validateConfirmPassword(formData.password, confirmPassword);
  };

  // 密码显示/隐藏切换
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  const toggleConfirmPasswordVisibility = () => {
    setShowConfirmPassword(!showConfirmPassword);
  };

  // 表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const { email, password, confirmPassword } = formData;
    let hasError = false;
    
    // 验证邮箱
    if (!email.trim()) {
      showError('email', '请输入邮箱或手机号');
      hasError = true;
    } else if (!validateEmail(email.trim())) {
      showError('email', '请输入有效的邮箱或手机号');
      hasError = true;
    }
    
    // 验证密码
    if (!password) {
      showError('password', '请输入密码');
      hasError = true;
    } else if (password.length < 8) {
      showError('password', '密码至少需要8位字符');
      hasError = true;
    }
    
    // 验证确认密码
    if (!confirmPassword) {
      showError('confirmPassword', '请确认密码');
      hasError = true;
    } else if (password !== confirmPassword) {
      showError('confirmPassword', '两次输入的密码不一致');
      hasError = true;
    }
    
    if (hasError) {
      return;
    }
    
    // 显示加载状态
    setIsSubmitting(true);
    
    try {
      // 调用注册API
      const response = await authAPI.register(email, email, password);
      
      // 注册成功，跳转到登录页面
      navigate('/login', { 
        state: { 
          message: '注册成功，请登录',
          success: true 
        }
      });
    } catch (err: any) {
      // 处理注册失败
      showError('email', err.message || '注册失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 键盘导航支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Enter' && !isSubmitting) {
        const form = document.getElementById('register-form') as HTMLFormElement;
        if (form) {
          form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isSubmitting]);

  // 获取密码强度条样式
  const getStrengthBarClasses = (barIndex: number) => {
    const baseClasses = 'h-1 flex-1 rounded-full transition-colors duration-300';
    
    if (passwordStrength.level <= 2) {
      return barIndex === 0 ? `${baseClasses} ${styles.passwordStrengthWeak}` : `${baseClasses} bg-gray-200`;
    } else if (passwordStrength.level <= 4) {
      return barIndex <= 1 ? `${baseClasses} ${styles.passwordStrengthMedium}` : `${baseClasses} bg-gray-200`;
    } else {
      return `${baseClasses} ${styles.passwordStrengthStrong}`;
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 注册表单容器 */}
      <div className="w-full max-w-md">
        {/* Logo和产品名称 */}
        <div className={`text-center mb-8 ${styles.fadeIn}`}>
          <div className="w-16 h-16 bg-primary rounded-2xl flex items-center justify-center mx-auto mb-4">
            <i className="fas fa-utensils text-white text-2xl"></i>
          </div>
          <h1 className="text-2xl font-bold text-text-primary mb-2">食算</h1>
          <p className="text-text-secondary">开始你的健康饮食之旅</p>
        </div>

        {/* 注册表单 */}
        <div className={`bg-white rounded-2xl shadow-form p-8 ${styles.fadeIn}`}>
          <div className="text-center mb-6">
            <h2 className="text-xl font-semibold text-text-primary mb-2">创建账户</h2>
            <p className="text-text-secondary text-sm">填写以下信息开始使用食算</p>
          </div>

          <form id="register-form" className="space-y-6" onSubmit={handleSubmit}>
            {/* 邮箱/手机号输入 */}
            <div className="space-y-2">
              <label htmlFor="email" className="block text-sm font-medium text-text-primary">
                邮箱/手机号 *
              </label>
              <div className="relative">
                <input
                  type="text"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleEmailChange}
                  onBlur={handleEmailBlur}
                  className={`w-full px-4 py-3 border rounded-lg transition-all duration-200 ${styles.formInputFocus} ${
                    formErrors.email ? 'border-danger' : 'border-border-light'
                  }`}
                  placeholder="请输入邮箱或手机号"
                  required
                />
                <i className="fas fa-envelope absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
              </div>
              {formErrors.email && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.email}</span>
                </div>
              )}
            </div>

            {/* 密码输入 */}
            <div className="space-y-2">
              <label htmlFor="password" className="block text-sm font-medium text-text-primary">
                密码 *
              </label>
              <div className="relative">
                <input
                  type={showPassword ? 'text' : 'password'}
                  id="password"
                  name="password"
                  value={formData.password}
                  onChange={handlePasswordChange}
                  className={`w-full px-4 py-3 pr-12 border rounded-lg transition-all duration-200 ${styles.formInputFocus} ${
                    formErrors.password ? 'border-danger' : 'border-border-light'
                  }`}
                  placeholder="请输入密码"
                  required
                />
                <button
                  type="button"
                  onClick={togglePasswordVisibility}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                >
                  <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
              
              {/* 密码强度指示器 */}
              {showPasswordStrength && (
                <div>
                  <div className="flex space-x-1 mb-2">
                    <div className={getStrengthBarClasses(0)}></div>
                    <div className={getStrengthBarClasses(1)}></div>
                    <div className={getStrengthBarClasses(2)}></div>
                  </div>
                  <p className="text-sm text-text-secondary">{passwordStrength.text}</p>
                </div>
              )}
              
              {formErrors.password && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.password}</span>
                </div>
              )}
            </div>

            {/* 确认密码输入 */}
            <div className="space-y-2">
              <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">
                确认密码 *
              </label>
              <div className="relative">
                <input
                  type={showConfirmPassword ? 'text' : 'password'}
                  id="confirm-password"
                  name="confirm-password"
                  value={formData.confirmPassword}
                  onChange={handleConfirmPasswordChange}
                  className={`w-full px-4 py-3 pr-12 border rounded-lg transition-all duration-200 ${styles.formInputFocus} ${
                    formErrors.confirmPassword ? 'border-danger' : 
                    showConfirmPasswordSuccess ? 'border-secondary' : 'border-border-light'
                  }`}
                  placeholder="请再次输入密码"
                  required
                />
                <button
                  type="button"
                  onClick={toggleConfirmPasswordVisibility}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                >
                  <i className={`fas ${showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
              
              {formErrors.confirmPassword && (
                <div className="text-danger text-sm">
                  <i className="fas fa-exclamation-circle mr-1"></i>
                  <span>{formErrors.confirmPassword}</span>
                </div>
              )}
              
              {showConfirmPasswordSuccess && (
                <div className="text-secondary text-sm">
                  <i className="fas fa-check-circle mr-1"></i>
                  <span>密码匹配</span>
                </div>
              )}
            </div>

            {/* 注册按钮 */}
            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full bg-primary text-white py-3 px-4 rounded-lg font-medium hover:bg-indigo-600 focus:outline-none focus:ring-4 focus:ring-indigo-200 transition-all duration-200 disabled:bg-gray-300 disabled:cursor-not-allowed"
            >
              <span>{isSubmitting ? '创建中...' : '创建账户'}</span>
              {isSubmitting && (
                <i className="fas fa-spinner fa-spin ml-2"></i>
              )}
            </button>
          </form>

          {/* 登录链接 */}
          <div className="text-center mt-6 pt-6 border-t border-border-light">
            <p className="text-text-secondary text-sm">
              已有账户？
              <Link
                to="/login"
                className="text-primary hover:text-indigo-600 font-medium transition-colors duration-200 ml-1"
              >
                立即登录
              </Link>
            </p>
          </div>
        </div>

        {/* 页脚 */}
        <div className={`text-center mt-8 ${styles.fadeIn}`}>
          <p className="text-text-secondary text-xs">
            © 2024 食算. 让健康饮食更简单
          </p>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;

